import { useState } from 'react';
import { IChooseAddress } from './type';

const useChooseAddress = (arg: IChooseAddress) => {
  const {options, level = 3, fieldNames = {text: 'text', value: 'value', children: 'children'}} = arg;
  const [selectData, setSelectData] = useState(() => {
    const showData: any[] = [];
    for (let i = 0; i < level; i++) {
      showData.push({
        key: String(i),
        [fieldNames.text]: '',
        [fieldNames.value]: 0,
        status: true,
        data: i === 0 ? options : []
      });
    }
    return showData;
  });

  const listClick = (index: number, item) => {
    setSelectData(() => {
      if (index < level) {
        selectData[index].name = item.name;
        if (index < level - 1) {
          selectData[index].status = false;
          selectData[index].name = item.name;
          selectData[index + 1].status = true;
          selectData[index + 1].name = '请选择';
          selectData[index + 1].data = item[fieldNames.children] ? item[fieldNames.children] : [];
          // 重新选择上一级，清空下级的选择
          if (!!selectData[index][fieldNames.value] && !!selectData[index + 1][fieldNames.value] && selectData[index][fieldNames.value] != item[fieldNames.value]) {
            selectData[index + 1][fieldNames.value] = 0;
            for (let i = index + 1; i < level; i++) {
              selectData[i].name = (i === index + 1) ? '请选择' : '';
              selectData[i].status = (i === index + 1);
            }
          }
        }
        selectData[index][fieldNames.value] = item[fieldNames.value];
      } else {
        selectData[index].status = true;
      }
      return [...selectData];
    });
  };

  const showListClick = (index: number) => {
    setSelectData(() => {
      return selectData.map((item, itemI) => {
        item.status = index === itemI;
        return item;
      });
    });
  };

  return {
    selectData,
    listClick,
    showListClick
  };
};

export default useChooseAddress;